package com.training.hatton.dropboxclient.content;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import com.training.hatton.dropboxclient.content.contract.MetadataContract;
import com.training.hatton.dropboxclient.content.db.DBHelper;

public class DropboxContentProvider extends ContentProvider {

	private DBHelper db;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int deletedRows = 0;
		if(selection == null && selectionArgs == null){
			db.getWritableDatabase().delete(DBHelper.METADATA_TABLE, null, null);
		}else{
			deleteWithEnter(selection, selectionArgs);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return deletedRows; 
	}

	private void deleteWithEnter(String selection, String[] selectionArgs) {
		Cursor cursor = db.getWritableDatabase().query(DBHelper.METADATA_TABLE, null, selection, selectionArgs, null, null, null);
		for(boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()){
			if (cursor.getInt(DBHelper.IS_DIR_COL_INDEX) > 0){
				deleteWithEnter(MetadataContract.MetadataColumns.PARENT + " = ? ", new String[] {cursor.getString(DBHelper.PATH_COL_INDEX)});
			}else{
				db.getWritableDatabase().delete(DBHelper.METADATA_TABLE, MetadataContract.MetadataColumns.PATH + " = ? ", new String[]{cursor.getString(DBHelper.PATH_COL_INDEX)});
			}
		}
		db.getWritableDatabase().delete(DBHelper.METADATA_TABLE, selection, selectionArgs);
	}

	@Override
	public String getType(Uri uri) {
		return MetadataContract.MetadataColumns.CONTENT_TYPE;
	}

	@Override
	public int bulkInsert(Uri uri, ContentValues[] values) {
		int ids = db.bulkInsert(values);
		getContext().getContentResolver().notifyChange(uri, null);
		return ids;
	}
	
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long id = db.addMetadata(values);
		Uri taskUri = ContentUris.withAppendedId(MetadataContract.MetadataColumns.CONTENT_URI, id);
		getContext().getContentResolver().notifyChange(taskUri, null);
		return taskUri;
	}

	@Override
	public boolean onCreate() {
		db = new DBHelper(getContext(), null);
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor cursor = db.getReadableDatabase().query(DBHelper.METADATA_TABLE, projection, selection, selectionArgs, null, null, sortOrder); 
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
		
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		db.getWritableDatabase().update(DBHelper.METADATA_TABLE, values, selection, selectionArgs);
		return 0;
	}


}
